<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>拼图游戏</title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
				text-align: center;
			}
			
			button {
				margin: 20px auto;
			}
			
			.box {
				width: 300px;
				height: 300px;
				border: 1px solid black;
				margin: auto;
				padding: 10px;
				position: relative;
			}
			
			.origin {
				position: absolute;
				width: 300px;
				height: 300px;
			}
			
			.imgbox {
				width: 100px;
				height: 100px;
				float: left;
				transition: all .3s ease;
			}
			
			img {
				width: 100%;
			}
		</style>
	</head>

	<body>
		<button>点击打乱图片</button>
		<div class="box">
			<div class="origin">
				<img src="img/ciri.jpg" />
			</div>
			<div class="imgbox"></div>
			<div class="imgbox"></div>
			<div class="imgbox"></div>
			<div class="imgbox"></div>
			<div class="imgbox"></div>
			<div class="imgbox"></div>
			<div class="imgbox"></div>
			<div class="imgbox"></div>
			<div class="imgbox"></div>
		</div>

		<script type="text/javascript">
			var btn = document.querySelector('button'),
				origin = document.querySelector('.origin'),
				box = document.querySelector('.box'),
				imgbox = document.getElementsByClassName('imgbox'),
				posi = [];

			//  变为绝对定位
			for(var j = 0; j < 9; j++) {
				posi.push([imgbox[j].offsetLeft, imgbox[j].offsetTop]);
			}

			for(var i = 0; i < 9; i++) {
				imgbox[i].style.position = "absolute";
				imgbox[i].style.left = posi[i][0] + 'px';
				imgbox[i].style.top = posi[i][1] + 'px';
			}

			btn.onclick = change;

			function change() {
				origin.style.display = 'none';

				// 随机图片下标
				var arr1 = [];
				for(var i = 0; i < 9; i++) {

					var img_index = Math.floor(Math.random() * 9);
					if(arr1.indexOf(img_index) < 0) {
						arr1.push(img_index);
					} else {
						i--;
					}
				}
				console.log(arr1)
				// 图片插入
				for(var j = 0; j < 9; j++) {
					imgbox[j].innerHTML = "<img src='img/" + arr1[j] + ".jpg' />";
					imgbox[j].setAttribute('data-index', arr1[j]);
				}

			}

			for(var i = 0; i < 9; i++) {
				switch_posi(imgbox[i]);
			}

			function switch_posi(obj) {
				obj.onclick = function() {

					var now_left = obj.style.left;
					var now_top = obj.style.top;
					for(var i = 0; i < 9; i++) {
						//  判断 相邻图片是否为空
						if(Math.abs(obj.offsetLeft - imgbox[i].offsetLeft) + Math.abs(obj.offsetTop - imgbox[i].offsetTop) == 100) {
							console.log(now_top)

							var theIndex = imgbox[i].getAttribute('data-index');

							if(theIndex == "0") {
								obj.style.left = imgbox[i].style.left;
								obj.style.top = imgbox[i].style.top;
								imgbox[i].style.left = now_left;
								imgbox[i].style.top = now_top;
							}
						}
					}
				}
			}
		</script>
	</body>

</html>